const Service = require('egg').Service

class DictService extends Service {
  // 获取字典子项
  async getItems({ dict_code }) {
    let res = await this.ctx.model.DictItem.findAll({
      where: { dict_code }
    })
    return res
  }
  /**
   * 新增字典项
   */
  async addItem({
    id,
    dict_code,
    item_name,
    item_desc,
    item_icon,
    pid = null,
    rank
  }) {
    // 查看是否存在排序rank字段
    if (rank == undefined) {
      const rank_res = await this.ctx.model.DictItem.findAll({
        where: { dict_code, pid },
        order: [['rank', 'DESC']]
      })
      if (rank_res.length > 0) {
        rank = rank_res[0].rank + 1
      }
    }
    // 存在id则更新
    if (id) {
      const res = await this.ctx.model.DictItem.update(
        {
          item_name,
          item_desc,
          item_icon,
          rank
        },
        {
          where: {
            id
          }
        }
      )
      return res
    } else {
      const res = await this.ctx.model.DictItem.create({
        dict_code,
        item_name,
        item_desc,
        item_icon,
        pid,
        rank
      })
      return res
    }
  }
  /**
   * 新增字典
   */
  async add({ id, dict_code, dict_name }) {
    let res = null
    if (!id) {
      res = await this.ctx.model.Dict.create({
        dict_code,
        dict_name
      })
    } else {
      res = await this.ctx.model.Dict.update(
        {
          dict_name
        },
        {
          where: { id }
        }
      )
    }
    return res
  }
  // 删除字典
  async destroy({ id }) {
    let res = await this.ctx.model.Dict.destroy({
      where: {
        id
      }
    })
    return res
  }
  // 更新字典项
  async update(params, id) {
    let res = await this.ctx.model.DictItem.update(params, {
      where: {
        id
      }
    })
    return res
  }
  // 删除字典项
  async destroyItem(id) {
    let res = await this.ctx.model.DictItem.destroy({
      where: {
        id
      }
    })
    return res
  }
  // 根据字典代码删除字典项
  async destroyItemByDictCode(dict_code) {
    let res = await this.ctx.model.DictItem.destroy({
      where: {
        dict_code
      }
    })
    return res
  }
}
module.exports = DictService
